package com.spa.common.generate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Locale;

import org.apache.commons.io.FileUtils;

import com.spa.common.generate.config.DataSourceConfig;
import com.spa.common.generate.config.EosGlobalConfig;
import com.spa.common.generate.po.TableInfo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Data;

/**
 * 代码工厂
 * 
 * @author zhaowei@xhzq.com
 * @date 2023/03/28
 */
@Data
public class EosCodeFactory {
    private TableInfo tableInfo;
    private EosGlobalConfig globalConfig;
    private DataSourceConfig dataSourceConfig;
    
    
    public EosCodeFactory(EosGlobalConfig globalConfig) {
        this.globalConfig = globalConfig;
    }
    
    public EosCodeFactory(EosGlobalConfig globalConfig, DataSourceConfig dataSourceConfig) {
        this.globalConfig = globalConfig;
        this.dataSourceConfig = dataSourceConfig;
        initConfig();
    }

    /**
     * 把配置数据注入模版，生成代码文件
     * 
     * @param templateFileName
     * @param type
     * @param data
     * @throws TemplateException
     * @throws IOException
     */
    public void generateFile(String type) throws TemplateException, IOException {
        // 创建目录
        FileUtils.forceMkdir(new File(globalConfig.getDirPath(type)));
        // 开流写入数据
        Writer out = new OutputStreamWriter(new FileOutputStream(globalConfig.getCodePath(type)),
            globalConfig.getSystemEncoding());// 生成的文件编码
        getConfiguration(type).process(globalConfig, out);// 结合模版生成代码文件
        // 关闭流
        out.close();
    }

    /**
     * 获取生成的文件路径
     * 
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public Template getConfiguration(String type) throws IOException {
        Configuration cfg = new Configuration();
        cfg.setClassForTemplateLoading(super.getClass(), globalConfig.getTemplatepath());
        cfg.setLocale(Locale.CHINA);
        cfg.setDefaultEncoding("UTF-8");
        return cfg.getTemplate(globalConfig.getTemplateName(type));
    }
    
    /**
     * 获取数据库表信息
     */
    private void initConfig() {
        if (dataSourceConfig == null) {
            throw new RuntimeException("dataSourceConfig is null");
        }
        if (globalConfig == null) {
            throw new RuntimeException("globalConfig is null");
        }
        tableInfo = dataSourceConfig.getTablesInfo(globalConfig.getTableName());
        this.globalConfig.setTableInfo(tableInfo);
    }

}
